// ChopperNavigation.cpp : Defines the entry point for the console application.
//
#include <windows.h>
#include <iostream>
#include "stdafx.h"
#include "SDL_syswm.h"

#include "chopperConstants.h"
#include "View.h"

using namespace std;

void getPressedKey(SDL_Event& sdlEvent);
void getReleasedKey(SDL_Event& sdlEvent);
void getPressedMouseButton(SDL_Event& sdlEvent);
void getPressedMouseMotion(SDL_Event& sdlEvent);

View* v;

static bool bRunning = true;
static int cameraState = STATIC_CAMERA;

static bool isMousePressed = false;
int xMousPos = 0;
int yMousPos = 0;

int _tmain(int argc, _TCHAR* argv[])
{
	v = new  View();

	if(SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		cerr << "Sdl init : " << SDL_GetError() << endl;
		return (EXIT_FAILURE);
	}

	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	putenv(strdup("SDL_VIDEO_CENTERED=1")); 

	SDL_Surface* pScreen = SDL_SetVideoMode(700, 700, 32, SDL_OPENGL);


	if(!pScreen)
	{
		cerr << "Echec creation de fenetre : " << SDL_GetError() << endl;
		return (EXIT_FAILURE);
	}

	v->init();


	while(bRunning)
	{
		SDL_Event sdlEvent;

		while(SDL_PollEvent( &sdlEvent) )
		{
			switch ( sdlEvent.type )
			{
				case SDL_QUIT:
					bRunning = false; 
					break;
				case SDL_KEYDOWN:
					getPressedKey(sdlEvent);
					break;
				case SDL_KEYUP:
					getReleasedKey(sdlEvent);
					break;
				case SDL_MOUSEBUTTONDOWN:
					getPressedMouseButton(sdlEvent);
					break;
				case SDL_MOUSEBUTTONUP:
					isMousePressed = false;
					break;
				case SDL_MOUSEMOTION:
					getPressedMouseMotion(sdlEvent);
					break;
			}
		}

		v->update();
		v->render();
		SDL_GL_SwapBuffers();
	}


	atexit(SDL_Quit);

	//free(mCconfigFileData);

	cout << "Fin normale du programme" << endl;

	return (EXIT_SUCCESS);
}



// Keyboard and mous acquisition
void getPressedKey(SDL_Event& sdlEvent)
{
	switch ( sdlEvent.key.keysym.sym )
	{
		case SDLK_LALT :
			cameraState = ROTATE_CAMERA;
			break;
		case SDLK_ESCAPE  :
			bRunning = false;
			break;
	}
}
void getReleasedKey(SDL_Event& sdlEvent)
{
	switch ( sdlEvent.key.keysym.sym )
	{
		case SDLK_LALT :
			cameraState = STATIC_CAMERA;
			break;
		case SDLK_ESCAPE  :
			bRunning = false;
			break;
	}
}
void getPressedMouseButton(SDL_Event& sdlEvent)
{
	switch ( sdlEvent.button.button )
	{
		case SDL_BUTTON_LEFT:
			isMousePressed = true;
			break;
		case SDL_BUTTON_WHEELUP :
			v->zoomInCamera(  );
			break;
		case SDL_BUTTON_WHEELDOWN :
			v->zoomOutCamera(  );
			break;
	}
}

void getPressedMouseMotion(SDL_Event& sdlEvent)
{
	if(isMousePressed )
	{
		float x = sdlEvent.motion.xrel;
		float y = sdlEvent.motion.yrel;

		v->rotateCamera(x, y);
	}
}
